package auth

import (
	"douhu_backend/internal/errors"
	"douhu_backend/internal/infra/logger"
	"douhu_backend/internal/model/auth"
	"regexp"
	"time"
)

// SendSMSCodeRequest 发送短信验证码请求
type SendSMSCodeRequest struct {
	Phone    string `json:"phone" validate:"required"`
	Typ      int    `json:"type" validate:"required"`
	ClientIP string `json:"client_ip"`
}

// SendSMSCode 发送短信验证码
// 返回 error 为业务错误（ServiceError）或系统错误
func (s *Service) SendSMSCode(req *SendSMSCodeRequest) error {
	// 验证手机号格式
	phoneRegex := regexp.MustCompile(`^1[3-9]\d{9}$`)
	if !phoneRegex.MatchString(req.Phone) {
		return errors.ErrPhoneFormat
	}

	logger.Infof("Send SMS code to phone: %s, type: %d", req.Phone, req.Typ)

	// 获取 SMS 服务
	smsService := s.SMS()

	// 根据验证码类型调用不同的发送方法
	var code string
	var err error

	switch req.Typ {
	case auth.SMSCodeTypeLogin:
		code, err = smsService.SendLoginCode(req.Phone)
	case auth.SMSCodeTypeRegister:
		code, err = smsService.SendRegisterCode(req.Phone)
	case auth.SMSCodeTypeReset:
		code, err = smsService.SendResetPasswordCode(req.Phone)
	default:
		return errors.ErrCodeType
	}

	if err != nil {
		logger.Errorf("Failed to send SMS code to phone %s: %v", req.Phone, err)
		return errors.ErrSMSSendFailed
	}

	// 保存验证码到数据库
	daoManager := s.manager.GetDAOManager()
	authDAO := daoManager.Auth

	// 创建验证码记录
	smsCode := &auth.SMSCode{
		Phone:      req.Phone,
		Code:       code,
		CodeType:   req.Typ,
		ExpireTime: time.Now().Add(10 * time.Minute), // 10分钟有效期
		UsedStatus: auth.SMSCodeUnused,
		ClientIP:   req.ClientIP,
	}

	if err := authDAO.CreateSMSCode(smsCode); err != nil {
		logger.Errorf("Failed to save SMS code: %v", err)
		return errors.ErrSaveSMSCode
	}

	logger.Infof("SMS code sent successfully to phone: %s, code: %s", req.Phone, code)
	return nil
}
